package com.tianshuai.gallerypic.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.lzy.ninegrid.NineGridView;
import com.yancy.gallerypick.R;

import java.util.List;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by magikliu on 2017/11/2.
 * Gallery 加载图片使用过
 */

public class ImagePreviewAdapter extends PagerAdapter {

    private Context context;
    private List<String> imageUrls;
    private View currentView;
    private OnCallBack onCallBack;

    public ImagePreviewAdapter(Context context, List<String> imageUrls) {
        this.context = context;
        this.imageUrls = imageUrls;
    }

    @Override
    public int getCount() {
        return imageUrls.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_photo_view, container, false);
        PhotoView imageView = view.findViewById(R.id.pv);
        String url = this.imageUrls.get(position);
        imageView.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
            @Override
            public void onPhotoTap(View view, float x, float y) {
                onCallBack.OnPhotoClick();
            }
        });
        //加载 图片
        NineGridView.getImageLoader().onDisplayImage(view.getContext(), imageView, url);
        container.addView(view);
        return view;
    }

    @Override
    public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        super.setPrimaryItem(container, position, object);
        currentView = (View) object;
    }

    public View getPrimaryItem() {
        return currentView;
    }

    public ImageView getPrimaryImageView() {
        return currentView.findViewById(R.id.pv);
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    public interface OnCallBack {
        void OnPhotoClick();
    }

    public void setOnPhotoClickListener(OnCallBack listener) {
        this.onCallBack = listener;
    }
}
